import 'package:flutter/material.dart';

class WidgetKeyPage extends StatefulWidget {
  const WidgetKeyPage({Key? key}) : super(key: key);

  @override
  _WidgetKeyPageState createState() => _WidgetKeyPageState();
}

class _WidgetKeyPageState extends State<WidgetKeyPage> {
  final boxColors = [Colors.red, Colors.green, Colors.blue];

  List<Widget> listBox = [];

  GlobalKey boxGlobalKey = GlobalKey();

  @override
  void initState() {
    super.initState();

    List<GlobalKey> globalKeyList =
        List.generate(3, (index) => GlobalKey()).toList();

    listBox = List.generate(
        3,
        (index) => Box(
              // key: ValueKey(index),
              // key: ObjectKey({ 'index': index }),
              // key: UniqueKey(),
              key: globalKeyList[index], // 如横竖屏切换，父组件由Column变成Row为了保持原有状态
              color: boxColors[index],
            )).toList();
  }

  Widget _getButtons() {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Positioned(
            right: 16,
            bottom: 32,
            child: IconButton(
              onPressed: () {
                setState(() {
                  listBox.shuffle();
                });
              },
              icon: const Icon(Icons.refresh),
            ),
          ),
          Positioned(
            top: 16,
            left: 32,
            child: IconButton(
              onPressed: () {},
              icon: const Icon(Icons.get_app),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    var portrait = MediaQuery.of(context).orientation == Orientation.portrait;

    return ListView(
      children: [
        portrait
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  ...listBox,
                  _getButtons(),
                ],
              )
            : Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ...listBox,
                  _getButtons(),
                ],
              ),
        Column(
          children: [
            Box(key: boxGlobalKey, color: Colors.cyan),
            IconButton(
              onPressed: () {
                // 获取state
                _BoxState boxState = boxGlobalKey.currentState! as _BoxState;
                print('_boxState._count: ${boxState._count}');
                // 获取widget
                Box box = boxGlobalKey.currentWidget! as Box;
                print('box.color: ${box.color}');
                // 获取widget的RenderBox 来获取显示的widget的size等属性
                RenderBox renderBox = boxGlobalKey.currentContext!
                    .findRenderObject() as RenderBox;
                print('renderBox.size: ${renderBox.size}');
              },
              icon: const Icon(Icons.data_array),
            )
          ],
        ),
      ],
    );
  }
}

class Box extends StatefulWidget {
  const Box({Key? key, required this.color}) : super(key: key);

  final Color color;

  @override
  State<Box> createState() => _BoxState();
}

class _BoxState extends State<Box> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 80,
      height: 80,
      margin: const EdgeInsets.all(10),
      child: ElevatedButton.icon(
        icon: const Icon(Icons.add),
        style: ButtonStyle(
            backgroundColor: MaterialStatePropertyAll(widget.color)),
        label: Text('$_count'),
        onPressed: () {
          setState(() {
            _count++;
          });
        },
      ),
    );
  }
}
